const express = require('express');
const router = express.Router();
const Club = require('../../models/clubsModels/create');

// 更新社团信息
router.put('/updateClub/:id', async (req, res) => {
  try {
    const { name, description, type, president } = req.body;
    const clubId = req.params.id;

    // 验证必填字段
    if (!name || !president) {
      return res.status(400).json({
        success: false,
        message: '社团名称和负责人为必填项'
      });
    }

    // 验证字段长度
    if (name.length > 100) {
      return res.status(400).json({
        success: false,
        message: '社团名称不能超过100个字符'
      });
    }

    if (president.length > 100) {
      return res.status(400).json({
        success: false,
        message: '负责人姓名不能超过100个字符'
      });
    }

    // 查找社团
    const club = await Club.findByPk(clubId);
    if (!club) {
      return res.status(404).json({
        success: false,
        message: '社团不存在'
      });
    }

    // 如果修改了社团名称，检查是否与其他社团重名
    if (name !== club.name) {
      const existingClub = await Club.findOne({
        where: { name }
      });
      if (existingClub) {
        return res.status(400).json({
          success: false,
          message: '该社团名称已存在'
        });
      }
    }

    // 更新社团信息
    const updatedClub = await club.update({
      name,
      description: description || null,
      type: type || null,
      president
    });

    res.status(200).json({
      success: true,
      message: '社团信息更新成功',
      data: {
        id: updatedClub.id,
        name: updatedClub.name,
        description: updatedClub.description,
        type: updatedClub.type,
        president: updatedClub.president,
        created_at: updatedClub.created_at
      }
    });

  } catch (error) {
    console.error('更新社团信息失败:', error);
    
    // 根据错误类型返回不同的错误信息
    if (error.name === 'SequelizeValidationError') {
      return res.status(400).json({
        success: false,
        message: '数据验证失败',
        errors: error.errors.map(err => err.message)
      });
    }

    res.status(500).json({
      success: false,
      message: '服务器错误，请稍后重试'
    });
  }
});

module.exports = router;